package com.suarte.webapp.action;

import com.suarte.core.Company;
import com.suarte.core.Contact;
import java.io.Serializable;
import java.util.List;
import org.appfuse.service.GenericManager;

/**
 * @date   Dec 21, 2010
 * @author Ggutierrez
 */
public class ContactForm extends BasePage implements Serializable {

    private GenericManager<Contact, Long> contactManager;
    private GenericManager<Company, Long> companyManager;
    private Contact contact = new Contact();
    private Company company;
    private Long id;

    public void setContactManager(GenericManager<Contact, Long> contactManager) {
        this.contactManager = contactManager;
    }

    public void setCompanyManager(GenericManager<Company, Long> companyManager) {
        this.companyManager = companyManager;
    }

    public Contact getContact() {
        return contact;
    }

    public void setContact(Contact contact) {
        this.contact = contact;
    }

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String delete() {
        contactManager.remove(contact.getId());
        addMessage("contact.deleted");

        return "list";
    }

    public String edit() {
        if (id != null) {
            contact = contactManager.get(id);
            company = contact.getCompany();
        } else {
            contact = new Contact();
        }

        return "edit";
    }

    public String add() {
        contact = new Contact();

        return "add";
    }

    public String save() {
        boolean isNew = (contact.getId() == null);

        if (company != null){
            contact.setCompany(company);
        }

        contactManager.save(contact);

        String key = (isNew) ? "contact.added" : "contact.updated";
        addMessage(key);

        if (isNew) {
            return "list";
        } else {
            return "edit";
        }
    }

    public List<Company> getCompanies(){
        return companyManager.getAll();
    }
}
